<template>
  <div>
    <el-upload
      ref="upload"
      class="img-upload"
      v-loading="uploading"
      element-loading-text="上传中，请耐心等待"
      :action="uploadUrl"
      accept=".jpg,.jpeg,.png,.bmp,.JPG,.JPEG,.PNG,.BMP"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :on-progress="handleProgress"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-exceed="handleExceed"
      multiple
      :limit="16"
      :file-list="fileList"
      list-type="picture-card"
    >
      <el-button size="mini" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且单张不超过1MB{{ extraTip }}</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" style="margin: 0">
    </el-dialog>
  </div>
</template>

<script>
const uploadApi = process.env.VUE_APP_IMG_UPLOAD_API
export default {
  name: 'ImgUploadMultiple',
  props: ['imgs', 'extraTip'],
  data() {
    return {
      fileList: [],
      urls: this.imgs,
      uploading: false,
      dialogVisible: false,
      dialogImageUrl: '',
      uploadUrl: uploadApi
    }
  },
  // mounted() {
  //   this.urls = this.imgs
  // },
  watch: {
    'imgs': function(newData, oldData) {
      const list = newData.split(',')
      this.fileList = []
      for (let i = 0; i < list.length; i++) {
        this.fileList.push({ url: list[i] })
      }
    }
  },
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      console.log(file)
      this.dialogVisible = true
    },
    handleRemove(file, fileList) {
      this.generateUrls(fileList)
      this.$emit('onChange')
    },
    handleChange(file, fileList) {
      this.generateUrls(fileList)
      this.$emit('onChange')
    },
    handleExceed(files, fileList) {
      this.$message.warning(`限制选择16张图片，本次选择了${files.length}个文件，共选择了${files.length + fileList.length}个文件，超出限制！`)
    },
    handleSuccess(response, file, fileList) {
      this.uploading = false
      if (response.code === 0) {
        const url = response.data
        file.url = url
        this.$message.success(`上传成功！`)
      } else {
        this.$message.warning(`上传失败！`)
      }
    },
    handleError() {
      this.uploading = false
      this.$message.warning(`上传失败！`)
    },
    handleProgress() {
      this.uploading = true
    },
    generateUrls(fileList) {
      var urls = ''
      for (let j = 0, len = fileList.length; j < len; j++) {
        urls += fileList[j].url + ','
      }
      this.urls = urls.substr(0, urls.length - 1)
    },
    clear() {
      this.url = ''
      this.$refs.upload.clearFiles()
    }

  }
}
</script>

<style scoped>

</style>
